<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="queryInfo.query" clearable @clear="clearSearch" @keyup.enter.native="searchUser" placeholder="请输入内容">
            <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="searchData" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column label="角色">
          <template slot-scope="scope">{{roleName[scope.row.roleId]}}</template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.stateBoolean" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUser(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 3, 4, 5]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-if="addOrEditDialog=='add'" v-model="addForm.username"></el-input>
          <el-input v-else v-model="addForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item v-if="addOrEditDialog=='add'" label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="roleId">
          <el-select v-model="addForm.roleId" placeholder="请选择角色">
            <el-option v-for="(value, key) in roleName" :key="key" :label="value" :value="key"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="comfirmUserDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqUser, reqUpdateState, reqDeleteUser, reqSaveUser, reqUpdateUser } from '@/api'
export default {
  data() {
    var checkEmai = (rule, value, cb) => {
      // 验证邮箱正则表达式
      const resEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (resEmail.test(value)) {
        // 合法邮箱
        return cb()
      }

      cb(new Error('亲输入合法邮箱！'))
    }

    var checkPhone = (rule, value, cb) => {
      // 验证手机号正则表达式
      // const resPhone = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      const resPhone = /^1[3456789]\d{9}$/
      if (resPhone.test(value)) {
        // 合法手机号
        return cb()
      }

      cb(new Error('亲输入合法手机号！'))
    }
    return {
      userList: [],
      searchUserList: [],
      roleName: {},
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 2
      },
      total: 3,
      addDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        phone: '',
        roleId: ''
      },
      addFormrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmai, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ],
        roleId: [{ required: true, message: '请选择用户角色', trigger: 'blur' }]
      },
      addOrEditDialog: ''
    }
  },

  computed: {
    // 模糊查询，当searchUserList有改变的时候就会返回一个计算后的新值
    searchData() {
      const num = this.queryInfo.pageNum
      const size = this.queryInfo.pageSize
      return this.searchUserList.slice((num - 1) * size, num * size)
    }
  },

  watch: {
    // 如果 `searchUserList` 发生改变，这个函数就会运行
    searchUserList: function(newUser, oldUser) {
      this.total = this.searchUserList.length
    }
  },

  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const result = await reqUser()
      if (result.code === 200) {
        this.userList = result.data.users
        this.searchUserList = result.data.users
        // 总页码
        this.total = result.data.users.length
        // 角色名和id
        const roleName = result.data.roles.reduce((pre, item) => {
          pre[item.id] = item.roleName
          return pre
        }, {})
        this.roleName = roleName
      } else {
        this.$message.error('获取用户列表失败！')
      }
    },

    // 分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryInfo.pageSize = val
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pageNum = val
    },

    // 用户状态改变
    async userStateChange(userinfo) {
      const state = userinfo.stateBoolean ? 1 : 0
      const id = userinfo.id
      const result = await reqUpdateState({ id, state }
      )
      if (result.code !== 200) {
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },

    // 模糊搜索用户
    searchUser() {
      const search = this.queryInfo.query
      if (search) {
        this.searchUserList = this.userList.filter(dataNews => {
          return Object.keys(dataNews).some(key => {
            return (
              String(dataNews[key])
                .toLowerCase()
                .indexOf(search) > -1
            )
          })
        })
      } else {
        this.searchUserList = this.userList
      }
    },

    // 清空模糊搜索框
    clearSearch() {
      this.searchUserList = this.userList
      this.total = this.userList.length
    },

    // 添加用户
    addUser() {
      this.addOrEditDialog = 'add'
      this.addDialogVisible = true
    },

    // 编辑用户
    editUser(userinfo) {
      this.addOrEditDialog = 'edit'
      this.addDialogVisible = true

      this.addForm = userinfo
      // 获取用户id
      this.addForm.id = userinfo.id
    },

    // 删除用户
    deleteUser(userinfo) {
      this.$confirm('是否要删除用户信息?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const id = userinfo.id
          const result = await reqDeleteUser(id)
          if (result.code === 204) {
            this.$message.success('删除用户成功！')
            // 重新获取用户刷新表格
            this.getUserList()
          } else {
            this.$message.error('删除用户失败！')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 确定对话框
    comfirmUserDialog() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 发起网络请求
        let res
        if (this.addOrEditDialog === 'add') {
          res = await reqSaveUser(this.addForm)
        } else {
          res = await reqUpdateUser(this.addForm)
        }
        if (res.code !== 201) {
          this.$message.error(
            `${this.addOrEditDialog === 'add' ? '添加' : '修改'}用户失败！`
          )
        }

        this.$message.success(
          `${this.addOrEditDialog === 'add' ? '添加' : '修改'}用户成功！`
        )
        // 重新获取数据
        this.getUserList()
        // 关闭对话框
        this.addDialogVisible = false
      })
    },

    // 对话框关闭回调
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
